<template>
  <div class="app-container">
    <el-container>
      <el-aside width="300px">
        <el-menu class="el-menu-vertical-demo" style="margin-top: 12px; ">
          <el-menu-item v-for="(item, index) in userList" :key="index" @click="handleClick(item)">
            <i class=" el-icon-menu"></i>
            <span slot="title">{{ item }}</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <div class="main-top">
          <div class="message" v-for="(item, index) in userMsg" :key="index"
            :style="item.fromUser == loginUserId ? 'text-align: right;' : 'text-align: left;'">
            [{{ item.sendTime }}] {{ item.fromUser }}：{{ item.msg }}
          </div>
        </div>
        <div class="main-bottom">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容" v-model="content">
          </el-input>
          <el-button type="primary" style="float: right; margin-top: 10px;" @click="sendMessage()">发送消息</el-button>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { merchantId } from "@/api/system/chatPage";

export default {
  name: "Chatpage",
  data() {
    return {
      userMsg: [],//单个用户的消息
      uniqueUserList: new Set(),//去重的用户列表
      userList: [],//用户列表
      msgList: [],//收到的所有消息
      ws: null, // WebSocket实例  
      isConnected: false, // 连接状态  
      loginUserId: null, // 登录账户ID  
      content: null, // 要发送的消息内容  
      toUserId: null, // 假设的接收用户ID 
    };
  },
  created() {
    this.getMerchantId();
  },
  methods: {
    //获取商家id
    getMerchantId() {
      merchantId()
        .then(res => {
          this.loginUserId = "merchantId" + res.data.merchantId;
          this.connectWebSocket();
        })
    },
    // 更新显示的消息
    updMsg() {
      this.userMsg = [];
      for (let ml of this.msgList) {
        if (ml.fromUser == this.toUserId || ml.toUser == this.toUserId) {
          ml.sendTime = this.$moment(ml.sendTime).format("YYYY-MM-DD HH:mm:ss")
          this.userMsg.push(ml);
        }
      }
    },
    //点击用户列表
    handleClick(item) {
      this.toUserId = item;
      this.updMsg();
    },
    //建立连接
    connectWebSocket() {
      const url = `ws://localhost:8080/system/websocket/${this.loginUserId}`;
      this.ws = new WebSocket(url);

      this.ws.onopen = () => {
        this.isConnected = true;
        console.log('WebSocket已连接');
        // 这里可以发送登录验证消息或其他初始化消息（如果需要的话）  
        // this.sendMessage({ fromUser: this.loginUserId, type: 'login' });  
      };

      this.ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        console.log('收到消息:', data);
        this.msgList.push(data || JSON.stringify(data)); // 假设消息中包含msg字段  
        for (let ml of this.msgList) {
          if (ml.fromUser != this.loginUserId && ml.fromUser != 'server') {
            if (this.uniqueUserList.has(ml.fromUser)) {
              // 如果存在，则删除  
              this.uniqueUserList.delete(ml.fromUser);
              // 先删后加 
              this.uniqueUserList.add(ml.fromUser);
            } else {
              this.uniqueUserList.add(ml.fromUser);
            }
          }
        }
        let reverseList = Array.from(this.uniqueUserList); // 转换成数组
        this.userList = reverseList.reverse(); // 倒序排列
        this.updMsg();
        // 清除点击过的用户的未读状态  
        // if (this.toUserId === data.fromUser) {
        //   delete this.unreadMessages[data.fromUser];
        // }
      };

      this.ws.onerror = (error) => {
        this.isConnected = false;
        console.error('WebSocket错误:', error);
      };

      this.ws.onclose = () => {
        this.isConnected = false;
        console.log('WebSocket连接已关闭');
        // 可以选择重新连接  
        // this.connectWebSocket();  
      };
    },
    closeWebSocket() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    sendMessage() {
      if (this.loginUserId == null || this.toUserId == null || this.content == null) {
        return;
      }
      if (this.ws && this.ws.readyState === WebSocket.OPEN && this.content) {
        const message = {
          fromUser: this.loginUserId,
          toUser: this.toUserId,
          msg: this.content,
          sendTime: Date.now()
        };
        this.ws.send(JSON.stringify(message));
        this.content = ''; // 发送后清空输入框  
      }
    },
  }
};
</script>

<style>
.main-top {
  width: 100%;
  height: 65%;
  background-color: #fff;
  border-radius: 5px;
}

.main-bottom {
  width: 100%;
  height: 30%;
  margin-top: 10px;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
}

.el-aside,
.el-main {
  height: 800px;
}
</style>